import React, { createContext, useState, useReducer, useEffect, useCallback } from 'react';
import Taro from '@tarojs/taro';
import { createReducerMapper, useMyReducer } from '@/utils/index';
import { MyOrderList_Web } from '@/pages/_server/_class/MyOrder/MyOrderList';
import { apiGetProductById } from '@/pages/_server/_api/ApiProduct/apiGetProductById';
import { apiGetApiOrderList } from '@/pages/_server/_api/ApiOrder/apiGetApiOrderList';

export type OrderContextType = {
    // orderExhibitionState: OrderExhibition;
    activeIndex: number;
    setActiveIndex: (state: number) => any;
    tabItems: any[];
    swiperRef: any;
};

export const OrderContext = createContext<OrderContextType>(undefined);

/** 页面渲染的列表 */
export type OrderExhibition = {
    orderList: MyOrderList_Web[];
    LoadingStatus: 'Loading' | 'complete' | 'nodata';
    pageIndex: number;
};

/** 处理reducer的函数 */
const handleMapper = createReducerMapper({
    initializer: null as OrderExhibition,
    handleMapper: {
        /**修改值 */
        setData: (state, payload: { newData: Partial<OrderExhibition> }) => {
            return { ...state, ...payload.newData };
        },
    },
});

const initialState: OrderExhibition = {
    orderList: [],
    LoadingStatus: 'Loading',
    pageIndex: 0,
};

/** 取到商品数据,此处对取商品数据的方法还需要进行一次包装,因为这需要合并多个接口,并不是单个接口自己玩 */
export const fetchorderList = async (searchFrom) => {
    const orderRes = await apiGetApiOrderList(searchFrom);
    let promiseArr = [];
    orderRes.data.forEach((order) => {
        let promise = apiGetProductById({
            productId: order.goodsId,
            artwork: true,
        }).then((res) => {
            order.immit_product(res.data);
        });
        promiseArr.push(promise);
    });
    await Promise.all(promiseArr);
    return orderRes;
};

/** 使用需要展示的列表 */
export const useOrderExhibitionList = (status: 'all' | 'unpaid' | 'paid' | 'cancelled') => {
    const [orderExhibitionState, OrderExhibitionDispatch] = useMyReducer({
        initializer: initialState,
        handleMapper,
    });
    useEffect(() => {
        let searchFrom = {
            status,
            pageIndex: 0,
        };
        // 页面加载完成时初始化列表
        fetchorderList(searchFrom).then((res) => {
            if (!res) return;
            freShListState({ orderList: res.data, LoadingStatus: 'complete' });
        });
    }, [OrderExhibitionDispatch, status]);
    /**刷新列表和加载状态 */
    const freShListState = useCallback(
        (params: Partial<OrderExhibition>) => {
            OrderExhibitionDispatch({
                type: 'setData',
                payload: {
                    newData: params,
                },
            });
        },
        [OrderExhibitionDispatch]
    );
    return {
        orderExhibitionState,
        OrderExhibitionDispatch,
        freShListState,
    };
};
